//
//  CartoonRecommendDetailViewController.m
//  Double
//
//  Created by 袁庆秋 on 15/5/23.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "CartoonRecommendDetailViewController.h"
#import <AFNetworking.h>
#import "RecommentDetailModel.h"
#import "DetailView.h"
#import <UIImageView+WebCache.h>
#import "CartoonPublicModel.h"
#import "PublicDetailViewController.h"
#import "PublicImageView.h"
#import "IntroView.h"
//#import "EpisodeView.h"
#import "CartoonPlay.h"
#import "AnimationCollectDatabase.h"
#import "AnimationCollectModel.h"
#import "HistoryModel.h"
#import "HistoryDatabase.h"

@interface CartoonRecommendDetailViewController ()<UIGestureRecognizerDelegate, UIWebViewDelegate>


@property (nonatomic, retain) UIScrollView *scroll;


@end

@implementation CartoonRecommendDetailViewController


- (void)dealloc
{
    [_lastup release];
    [_scroll release];
    [_dic release];
    [_episodeArray release];
    [_categoryArray release];
    [_fromSiteArray release];
    [_watchUserArray release];
    [_iD release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dic = [NSMutableDictionary dictionary];
        self.categoryArray = [NSMutableArray array];
        self.episodeArray = [NSMutableArray array];
        self.fromSiteArray = [NSMutableArray array];
        self.watchUserArray = [NSMutableArray array];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self startConnection];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationItem.title = self.titleName;
    
    UIBarButtonItem *button1 = [[[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(buttonAction:)]autorelease];
    self.navigationItem.rightBarButtonItem = button1;
}


#pragma mark -
#pragma mark 收藏点击事件

- (void)buttonAction:(id)sender
{
    NSInteger AnimationId = [self.iD integerValue];
    NSString * AnimationName = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"name"]];
    NSString * AnimationPic = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"cover"]];
    AnimationCollectModel * model = [AnimationCollectModel AnimationCollectModelWithAnimationId:AnimationId AnimationName:AnimationName AnimationPic:AnimationPic];
    [AnimationCollectDatabase insertWithModel:model];
}

#pragma mark -
#pragma mark 数据请求
- (void)startConnection
{
    
    NSString *url = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Api&ios=23&pad=0&a=getInfo&video_id=%@&uid=(null)", self.iD];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.categoryArray = [self.dic objectForKey:@"categorys"];
        self.episodeArray = [self.dic objectForKey:@"episode"];
        self.fromSiteArray = [self.dic objectForKey:@"from_site"];
        self.watchUserArray = [self.dic objectForKey:@"watchUser"];
        
        //数据请求之后再铺设页面
        [self createTopView];
        [self createCenterView];
        [self createBottomView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


#pragma mark -
#pragma mark 铺设详情页面上半部分
- (void)createTopView
{
    DetailView *detail = [[DetailView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 4)];
    [self.view addSubview:detail];
    [detail release];
    
    //显示图片
    [detail.showImage sd_setImageWithURL:[NSURL URLWithString:[self.dic objectForKey:@"cover"]] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
    
    //名称
    detail.titleLabel.text = [self.dic objectForKey:@"name"];
    //地区
    detail.positionLabel.text = [self.dic objectForKey:@"area"];
    //主演
    NSString *character = [self.dic objectForKey:@"character"];
    detail.categorysLabel.text = [NSString stringWithFormat:@"主演:%@", character];
    //更新时间
    NSString *time = [self.dic objectForKey:@"update_string"];
    detail.updateLabel.text = [NSString stringWithFormat:@"更新时间:%@", time];
    //更新至11集
//    detail.totalNumLabel.text = [NSString stringWithFormat:@"更新至%@集", self.lastup];
//    if ([self.lastup hasPrefix:@"更新"] || [self.lastup hasPrefix:@"已完结"]) {
//        detail.totalNumLabel.text = self.lastup;
//    } else {
//        if ([self.is_over isEqualToString:[NSString stringWithFormat:@"1"]]) {
//            detail.totalNumLabel.text = [NSString stringWithFormat:@"已完结 全%@集", self.lastup];
//        } else if ([self.is_over isEqualToString:[NSString stringWithFormat:@"0"]]) {
//            detail.totalNumLabel.text = [NSString stringWithFormat:@"更新至%@集", self.lastup];
//        }
//    }
    
    //更新至..集 / 已完结..集
    NSString *str = [self.dic objectForKey:@"cur_num"];
    //是否完结
    NSString *str1 = [self.dic objectForKey:@"is_over"];
    
    if ([str1 isEqualToString:@"1"]) {
        if ([str hasPrefix:@"已"]) {
            detail.totalNumLabel.text = str;
        } else {
            detail.totalNumLabel.text = [NSString stringWithFormat:@"已完结,共%@集", str];
        }
    } else if ([str1 isEqualToString:@"0"]) {
        if ([str hasPrefix:@"更新"]) {
            detail.totalNumLabel.text = str;
        } else {
            detail.totalNumLabel.text = [NSString stringWithFormat:@"更新至%@集", str];
        }
    }
    
    
    //评分
    NSInteger total_num = [[self.dic objectForKey:@"score_total_num"] integerValue];
    NSInteger person_num = [[self.dic objectForKey:@"score_person_num"] integerValue];
    NSString *score = [NSString stringWithFormat:@"%ld", total_num/person_num];
    detail.score.text = [NSString stringWithFormat:@"%@分", score];
    detail.score.textColor = [UIColor orangeColor];
    
    
    
    
    //立即观看按钮
    [detail.watchBtn addTarget:self action:@selector(watchAction:) forControlEvents:UIControlEventTouchUpInside];
    //下载按钮
    [detail.downLoadBtn addTarget:self action:@selector(downLoadAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark -
#pragma mark 观看、下载按钮
- (void)watchAction:(id)sender
{
    //从数组里取出来选中集的信息
    NSDictionary *dic = [self.episodeArray objectAtIndex:0];
    //选中集的视频请求网址
    NSString *url = [dic objectForKey:@"mUrl"];
    CartoonPlay *play = [[CartoonPlay alloc] init];
    play.url = url;
    [self presentViewController:play animated:YES completion:nil];
    
    NSInteger HistoryId = [self.iD integerValue];
    NSString * HistoryName = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"name"]];
    NSString * HistoryPic = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"cover"]];
    HistoryModel * model = [HistoryModel HistoryModelWithHistoryId:HistoryId HistoryName:HistoryName HistoryPic:HistoryPic];
    [HistoryDatabase insertWithModel:model];
}

- (void)downLoadAction:(id)sender
{
    NSString *message = @"该功能正在开发中，请期待2.0版本😄";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    [alert release];
}

#pragma mark -
#pragma mark 铺设中间“播放源”和“大家也在看”

- (void)createCenterView
{
//播放源
    UILabel *fromSiteLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, self.view.frame.size.height / 4 + 5, self.view.frame.size.width / 4, 40)];
    fromSiteLabel.text = @"播放源: ";
    [self.view addSubview:fromSiteLabel];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 4 + 10, self.view.frame.size.height / 4 + 5, 40, 40)];
    [button setImage:[UIImage imageNamed:@"youku.jpg"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(playFilmAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
//大家也在看
    UILabel *publicLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, self.view.frame.size.height / 4 + 50, self.view.frame.size.width / 3, 40)];
    publicLabel.text = @"大家也在看:";
    [self.view addSubview:publicLabel];
    
    for (int i = 0; i < self.watchUserArray.count; i++) {
        PublicImageView *showImage = [[PublicImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width / 3 + 10) + i * (self.view.frame.size.width / 15 * 2 - 2), self.view.frame.size.height / 4 + 50, self.view.frame.size.width * 2 / 15 - 12, 40)];
        showImage.userInteractionEnabled = YES;
        showImage.clipsToBounds = YES;
        showImage.layer.cornerRadius = (self.view.frame.size.width * 2 / 15 - 12) / 2;
        
        showImage.dic= [self.watchUserArray objectAtIndex:i];
        NSString *imageString = [showImage.dic objectForKey:@"head_pic"];
        [showImage sd_setImageWithURL:[NSURL URLWithString:imageString] placeholderImage:[UIImage imageNamed:@"avatar.jpg"] options:SDWebImageRetryFailed];
        showImage.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [showImage addGestureRecognizer:tap];
        [self.view addSubview:showImage];
        
    }
}

#pragma mark -
#pragma mark 创建下面的介绍和播放界面
- (void)createBottomView
{
    UIButton *introBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 4 + 100, self.view.frame.size.width / 2, self.view.frame.size.height / 4 - 100)];
    [introBtn setTitle:@"简介" forState:UIControlStateNormal];
    [introBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [introBtn setBackgroundColor:[UIColor lightGrayColor]];
    [introBtn addTarget:self action:@selector(introViewShow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:introBtn];
    
    UIButton *epiBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2, self.view.frame.size.height / 4 + 100, self.view.frame.size.width / 2, self.view.frame.size.height / 4 - 100)];
    [epiBtn setTitle:@"剧集列表" forState:UIControlStateNormal];
    [epiBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [epiBtn setBackgroundColor:[UIColor lightGrayColor]];
    [epiBtn addTarget:self action:@selector(episodeViewShow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:epiBtn];
    
    self.introView = [[IntroView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2 , self.view.frame.size.width, self.view.frame.size.height / 2 - 49)];
    
//    self.introView.introLabel.text = [self.dic objectForKey:@"intro"];
    [self.introView zidingyiScroll:[self.dic objectForKey:@"intro"]];
    
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, self.view.frame.size.width, self.view.frame.size.height / 2 - 49)];
    
    [self.view addSubview:self.scroll];
    [self.view addSubview:self.introView];
}

- (void)introViewShow:(id)sender
{
    self.scroll.alpha = 0;
    self.introView.alpha = 1;
    [self.view insertSubview:self.introView aboveSubview:self.scroll];
}

- (void)episodeViewShow:(id)sender
{
    self.scroll.contentSize = CGSizeMake(self.view.frame.size.width, 40 * self.episodeArray.count / 4 + 50);
    [self.view insertSubview:self.scroll aboveSubview:self.introView];
    self.introView.alpha = 0;
    self.scroll.alpha = 1;
    self.scroll.backgroundColor = [UIColor whiteColor];
    

    
    NSInteger count = self.episodeArray.count;
    CGFloat width = self.view.frame.size.width / 5;
    for (int i = 0; i < count; i++) {
        UIButton *playBtn = [[UIButton alloc] initWithFrame:CGRectMake(10 + i % 4 *(width + 10), 10 + i / 4 * 40, width, 30)];
        [playBtn setTitle:[NSString stringWithFormat:@"第%d集", i + 1] forState:UIControlStateNormal];
        playBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [playBtn setBackgroundColor:[UIColor lightGrayColor]];
        [playBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
        [playBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [playBtn addTarget:self action:@selector(playFilmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        playBtn.tag = i + 1;
        [self.scroll addSubview:playBtn];
    }
}

#pragma mark -
#pragma mark 点击选集数，播放视频
- (void)playFilmBtnClick:(id)sender
{
    UIButton *btn = (UIButton *)sender;
//从数组里取出来选中集的信息
    NSDictionary *dic = [self.episodeArray objectAtIndex:btn.tag - 1];
//选中集的视频请求网址
    NSString *url = [dic objectForKey:@"mUrl"];
    CartoonPlay *play = [[CartoonPlay alloc] init];
    play.url = url;
    [self presentViewController:play animated:YES completion:nil];

}



#pragma mark -
#pragma mark 点击播放源“优酷”图标，播放视频第一集
- (void)playFilmAction:(id)sender
{
    NSDictionary *dic = [self.episodeArray objectAtIndex:0];
    NSString *str = [dic objectForKey:@"mUrl"];
    CartoonPlay *play = [[CartoonPlay alloc] init];
    play.url = str;
    [self presentViewController:play animated:YES completion:nil];
}

#pragma mark -
#pragma mark 所有观众头像点击进入观众主页
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    
}



@end
